import classNames from 'classnames';
import React from 'react';
import { polyfill } from 'react-lifecycles-compat';
import { CommonInterface, JSXPropsInterface } from '../../interfaces/common.interface';
import { SizeType, positionType } from '../../interfaces/types';
import { handleSize, JSXProps } from '../../utils/handleJSXProps';
import { typeReplace } from '../../utils/muguetDash';
import './style/red.css';

const prefix = 'm-red';

const customRedProps = [
	'size',
	'shape',
	'count',
	'place',
	'gradients',
	'children',
	'className',
	'style'
]

interface RedProps extends CommonInterface {
	count?: number;
	place?: positionType;
}

class Red extends React.Component<RedProps, any> {
	redRef: React.RefObject<any>;

	private static readonly defaultProps = {
		size: 'normal',
		place: 'topRight',
		shape: 'square'
	}
	redPlace: positionType;

	constructor(props) {
		super(props);
		this.redRef = React.createRef();
	}

	componentDidMount() {
		const redEle = this.redRef.current as HTMLElement;
		const siblingEle = redEle.nextElementSibling as HTMLElement;

		redEle.style.left = siblingEle.offsetLeft +
			(this.redPlace === 'topRight' || this.redPlace === 'bottomLeft' ? siblingEle.offsetWidth : 0) -
			redEle.offsetWidth / 2 + 'px';

		redEle.style.top = siblingEle.offsetTop +
			(this.redPlace === 'bottomRight' || this.redPlace === 'bottomLeft' ? siblingEle.offsetHeight : 0) -
			redEle.offsetWidth / 2 + 'px';
	}

	handleExtraProps = (): JSXPropsInterface<RedProps> => {
		const redProps = JSXProps<RedProps>(this.props, customRedProps);
		const { customProps } = redProps;
		customProps.size = handleSize(customProps.size as SizeType);
		return redProps;
	}

	handleClassName = (classProps) => {
		const {
			size,
			className,
			shape
		} = classProps;
		return {
			containerName: classNames({
				[`${prefix}-container`]: true,
			}),
			redName: classNames({
				[`${prefix}-default`]: true,
				[`${prefix}-shape-${shape}`]: shape,
				[`${classNames(className)}`]: className,
				[`${prefix}-size-${size}`]: typeReplace(size!, 'String', false),
			})
		}
	}

	render() {
		const { nativeProps, customProps } = this.handleExtraProps();
		const className = this.handleClassName(customProps);
		const mergeStyle = {
			...typeReplace(customProps.size as Object, 'Object', {}),
			...typeReplace(customProps.style as Object, 'Object', {})
		}
		this.redPlace = customProps.place as positionType;
		return (
			<div
				{...nativeProps}
				className={className.containerName}
			>
				<div
					style={mergeStyle}
					ref={this.redRef}
					className={className.redName}
				>{customProps.count! >= 0 ? customProps.count : null}</div>
				{React.Children.only(customProps.children)}
			</div>
		)
	}
}

polyfill(Red);
export default Red;
